<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const dateMinusDay = (date, days) => {
  const d = new Date(date)
  d.setDate(d.getDate() - days)
  return d
}
const lastWeek = dateMinusDay(new Date(), 7)
// 添加日期范围ref
const dateRange = ref({ start: lastWeek, end: new Date() })


const operator = ref('ALL')
const networkType = ref('ALL')
const networkQuality = ref('下行速率')

// 选项数据
const operatorOptions = ['ALL', 'CMCC', 'CUCC', 'CTCC']
const networkTypeOptions = ['ALL', '5G', '4G', '3G', '2G']
const networkQualityOptions = ['下行速率', '上行速率', '延迟']

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const fetchChartData = async () => {
  try {
    const response = await axios.get('/api/phone/network-quality-rank', {})
    console.log(response)

    const { legends, xaxisData, seriesData } = response.data.data

    if (!chart) return

    const option: echarts.EChartsOption = {
      title: {
        text: '热门手机网络质量排名',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: (params: any) => {
          const unit = networkQuality.value === '延迟' ? 'ms' : 'Mbps'
          return `${params[0].name}<br/>${params[0].value} ${unit}`
        },
        show: true
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xaxisData,
        axisLabel: {
          interval: 0,
          rotate: 0,
          textStyle: {
            fontSize: 12,
            align: 'center'
          },
          overflow: 'break'
        }
      },
      yAxis: {
        type: 'value',
        name: networkQuality.value === '延迟' ? 'ms' : 'Mbps'
      },
      series: [
        {
          type: 'bar',
          data: seriesData[0],
          itemStyle: {
            color: '#FF7F50'
          },
          label: {
            show: false,
          },
          emphasis: {
            label: {
              show: true,
              position: 'top',
              formatter: (params: any) => {
                const unit = networkQuality.value === '延迟' ? 'ms' : 'Mbps'
                return `${params.value} ${unit}`
              },
              fontSize: 12,
              color: '#333'
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.1)'
            }
          },
          barWidth: '40%'
        }
      ]
    }

    chart.setOption(option)
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

// 初始化图表
onMounted(() => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    fetchChartData()
  }
  window.addEventListener('resize', () => chart?.resize())
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', () => chart?.resize())
  chart?.dispose()
})
</script>

<template>
  <div class="network-quality-rank">
    <div class="mb-4 query-panel">
      <div class="flex items-center gap-4">
        <div class="query-item">
          <VaDateInput
            v-model="dateRange"
            mode="range"
            label="日期范围"
            placeholder="选择日期范围"
            class="date-input"
          />
        </div>

        <div class="query-item">
          <VaSelect
            v-model="operator"
            :options="operatorOptions"
            label="运营商"
            class="select-input"
          />
        </div>

        <div class="query-item">
          <VaSelect
            v-model="networkType"
            :options="networkTypeOptions"
            label="网络制式"
            class="select-input"
          />
        </div>

        <div class="query-item">
          <VaSelect
            v-model="networkQuality"
            :options="networkQualityOptions"
            label="网络质量"
            class="select-input"
          />
        </div>

        <VaButton
          type="primary"
          @click="fetchChartData"
          class="query-button"
        >
          查询
        </VaButton>
      </div>
    </div>

    <div ref="chartRef" class="chart-container" style="height: calc(100vh - 290px)"></div>
  </div>
</template>

<style scoped>
.network-quality-rank {
  padding: 16px;
}

.query-panel {
  background: white;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.chart-container {
  background: white;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  height: 500px;
}

.query-item {
  display: flex;
  align-items: flex-end;
}

.date-input {
  width: 220px !important;
}

.select-input {
  width: 150px !important;
}

.query-button {
  height: 36px;
  margin-left: 8px;
  margin-bottom: 1px;
}

</style>
